package com.mk.admin.util;

import com.alibaba.fastjson2.JSONObject;
import com.mk.admin.api.Api;
import com.mk.admin.api.Basic;
import com.mk.admin.api.Body;
import com.mk.admin.api.Params;
import com.mk.admin.model.entity.ApiEntity;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Objects;

/**
 * OKHttp工具类
 */
@Slf4j
public class HttpTool {

    /**
     * 调用接口名称 "transactionCode": "opt_0001"
     *
     * @param transactionCode
     * @return
     */
    public static JSONObject postJson(String transactionCode, String detail) {
        return post(transactionCode, detail);
    }

    public static JSONObject postJson(String transactionCode, Object detail) {
        return post(transactionCode, JSONObject.toJSONString(detail));
    }

    private static JSONObject post(String transactionCode, String detail) {
        ApiEntity entity = Api.apiEntity;
        String result = "";

        Body body = Body.builder()
                .params(Params.builder()
                        .basic(Basic.builder()
                                .aspCode(entity.getAspCode())
                                .appId(entity.getAppId())
                                .hospitalCode(entity.getHospitalCode())
<<<<<<< HEAD
                                .medicalCombo(0)
                                .branchCode("01")
                                .operatorNo("00")
                                .terminalId(null)
                                .version(null)
=======
                                .medicalCombo(entity.getMedicalCombo())
                                .branchCode(entity.getBranchCode())
                                .operatorNo(entity.getOperatorNo())
                                .terminalId(entity.getTerminalId())
                                .version(entity.getVersion())
>>>>>>> f2106939b942a7ac2c3470910120a35364fbfaac
                                .transactionCode(transactionCode)
                                .build())
                        .detail(JSONObject.parseObject(detail))
                        .build())
                .timeStamp(System.currentTimeMillis())
                .build();
<<<<<<< HEAD
        log.info("请求报文{}", JSONObject.toJSONString(body));
=======
        log.info("请求报文{}{}", transactionCode, JSONObject.toJSONString(body));
>>>>>>> f2106939b942a7ac2c3470910120a35364fbfaac
        try {
            SimpleClientHttpRequestFactory tokenFactory = new SimpleClientHttpRequestFactory();
            tokenFactory.setConnectTimeout(20000);
            tokenFactory.setReadTimeout(20000);
            RestTemplate tokenTemplate = new RestTemplate(tokenFactory);
            org.springframework.http.MediaType type = org.springframework.http.MediaType.parseMediaType("application/json");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(type);
            headers.add("Authorization", "Bearer " + getToken(entity));
            headers.add("Content-Type", "application/json");
            headers.add("TENANT-CODE", entity.getAspCode());
            log.info("请求头{}", JSONObject.toJSONString(headers));
            HttpEntity<String> request = new HttpEntity<>(JSONObject.toJSONString(body), headers);
            String api = entity.getApiUrl();
            log.info("请求地址{}", api);
            result = tokenTemplate.postForObject(api, request, String.class);
<<<<<<< HEAD
            log.info("远程返回结果{}", result);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("远程连接异常{}", e.getMessage());
=======
            log.info("远程返回结果{}{}", transactionCode, result);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("远程连接异常{}{}", transactionCode, e.getMessage());
>>>>>>> f2106939b942a7ac2c3470910120a35364fbfaac
            throw new RuntimeException(e);
        }
        return JSONObject.parseObject(result);
    }

    public static JSONObject pdf(String picUrl) {
        ApiEntity entity = Api.apiEntity;
//        String result = "";
//
//        Body body = Body.builder()
//                .params(Params.builder()
//                        .basic(Basic.builder()
//                                .aspCode(entity.getAspCode())
//                                .appId(entity.getAppId())
//                                .hospitalCode(entity.getHospitalCode())
//                                .medicalCombo(0)
//                                .branchCode("01")
//                                .operatorNo("00")
//                                .terminalId(null)
//                                .version(null)
//                                .build())
//                        .detail(JSONObject.parseObject(detail))
//                        .build())
//                .timeStamp(System.currentTimeMillis())
//                .build();
//        log.info("请求报文{}", JSONObject.toJSONString(body));
//
//        try {
//            SimpleClientHttpRequestFactory tokenFactory = new SimpleClientHttpRequestFactory();
//            tokenFactory.setConnectTimeout(20000);
//            tokenFactory.setReadTimeout(20000);
//            RestTemplate tokenTemplate = new RestTemplate(tokenFactory);
//            org.springframework.http.MediaType type = org.springframework.http.MediaType.parseMediaType("application/json");
//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(type);
//            headers.add("Authorization", "Bearer " + getToken(entity));
//            headers.add("Content-Type", "application/json");
//            headers.add("TENANT-CODE", entity.getAspCode());
//            log.info("请求头{}", JSONObject.toJSONString(headers));
//            HttpEntity<String> request = new HttpEntity<>(JSONObject.toJSONString(body), headers);
//            String api = entity.getPicUrl();
//            log.info("请求地址{}", api);
//            result = tokenTemplate.postForObject(api, request, String.class);
//            log.info("远程返回结果{}", result);
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("远程连接异常{}", e.getMessage());
//            throw new RuntimeException(e);
//        }
//        return JSONObject.parseObject(result);
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("multipart/form-data; boundary=--------------------------061277239372512184684040");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("picUrl", picUrl)
                .build();
        Request request = new Request.Builder()
                .url(entity.getPdfUrl())
                .method("POST", body)
                .addHeader("Authorization", "Bearer " + getToken(entity))
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .addHeader("Accept", "*/*")
                .addHeader("Host", entity.getHost())
                .addHeader("Connection", "keep-alive")
                .addHeader("Content-Type", "multipart/form-data;")
                .build();
        String result = "";
        try {
            ResponseBody responseBody = client.newCall(request).execute().body();
            result = responseBody == null ? "" : responseBody.string();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSONObject.parseObject(result);
    }

    /**
     * 得到token
     *
     * @param entity
     * @return
     */
    private static String getToken(ApiEntity entity) {
        SimpleClientHttpRequestFactory tokenFactory = new SimpleClientHttpRequestFactory();
        tokenFactory.setConnectTimeout(20000);
        tokenFactory.setReadTimeout(20000);
        RestTemplate tokenTemplate = new RestTemplate(tokenFactory);
        org.springframework.http.MediaType type = org.springframework.http.MediaType.parseMediaType("application/json");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(type);
        headers.add("TENANT-CODE", entity.getAspCode());
        headers.add("Authorization", "Basic " + entity.getToken());
        HttpEntity<String> request = new HttpEntity<>(headers);
        String tokenUrl = entity.getTokenUrl();
        tokenUrl += "?scope=" + entity.getScope() + "&grant_type=" + entity.getGrantType();
        String result = tokenTemplate.postForObject(tokenUrl, request, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return String.valueOf(Objects.requireNonNull(jsonObject).get("access_token"));
    }

}

